//
//  ArticleViewController.m
//  OneDay
//
//  Created by lanou3g on 15/10/31.
//  Copyright © 2015年 oneDay. All rights reserved.
//

#import "ArticleViewController.h"
#import "HJCarouselViewLayout.h"
#import "ArticleCollectionViewCell.h"
#import "ArticleDetailViewController.h"
#import <Reachability/Reachability.h>

@interface ArticleViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSArray *imageArray;

@end

static NSString *identifier = @"Cell";

@implementation ArticleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"OneDay美文";
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    // 开启网络链接
    Reachability *reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
    // 开启一个通知 来监听网络状态的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    // 开启网络监控
    [reach startNotifier];
    
}
- (void)reachabilityChanged:(NSNotification *)changed
{
    /*
     网络是否链接 -- isReachable
     WiFi ---- isReachableViaWiFi
     2G,3G --- isReachableViaWWAN
     */
    // 获取 View 里开启的哪个网络连接
    Reachability *reach = [changed object];
    if (![reach isReachable]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"小天检测到您没有开启网络哦😭" preferredStyle:UIAlertControllerStyleAlert];
        // 创建一个ok按钮
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"我要去开网!!!" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSLog(@"%@", action.title);
        }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        [self setCollectionView];
        self.imageArray = @[@"1.jpg", @"2.jpg", @"3.jpg", @"4.jpg", @"5.jpg", @"6.jpg", @"7.jpg", @"8.jpg", @"9.jpg", @"10.jpg"];
        [self requestArticleDataWithUrl:kArticleUrl block:^() {
            [self.collectionView reloadData];
        }];
    }
}


- (void)setCollectionView
{
    HJCarouselViewLayout *layOut = [[HJCarouselViewLayout alloc] initWithAnim:HJCarouselAnimCoverFlow];
    [layOut setItemSize:CGSizeMake(0.8 * kWidth, 0.8 * kWidth)];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layOut];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor colorWithRed:202.67 / 255.0 green:235.17 / 255.0 blue:216.58 / 255.0 alpha:1];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    [self.collectionView registerClass:[ArticleCollectionViewCell class] forCellWithReuseIdentifier:identifier];
    [self.view addSubview:self.collectionView];
}

// 控制在每个分区显示cell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
// 设置cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ArticleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor cyanColor];
    cell.layer.cornerRadius = cell.frame.size.width / 15;
    ArticleModel *model = self.dataArray[indexPath.row];
    // 打乱图片数组，
    
    
    cell.bgImageView.image = [UIImage imageNamed:self.imageArray[indexPath.row]];
    cell.model = model;
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    ArticleDetailViewController *artDetaVC = [[ArticleDetailViewController alloc] init];
    ArticleModel *model = self.dataArray[indexPath.row];
    artDetaVC.needID = model.ID;
    [self.navigationController pushViewController:artDetaVC animated:YES];
}


// 返回这个collectionView是否可以被选择
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSIndexPath *curIndexPath = [self curIndexPath];
    if (indexPath.row == curIndexPath.row) {
        return YES;
    }
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    return NO;
}

- (NSIndexPath *)curIndexPath {
    NSArray *indexPaths = [self.collectionView indexPathsForVisibleItems];
    NSIndexPath *curIndexPath = nil;
    NSInteger curzIndex = 0;
    for (NSIndexPath *path in indexPaths.objectEnumerator) {
        UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:path];
        if (!curIndexPath) {
            curIndexPath = path;
            curzIndex = attributes.zIndex;
            continue;
        }
        if (attributes.zIndex > curzIndex) {
            curIndexPath = path;
            curzIndex = attributes.zIndex;
        }
    }
    return curIndexPath;
}


#pragma mark -- 文章界面请求数据
- (void)requestArticleDataWithUrl:(NSString *)url block:(void (^)())block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [request setHTTPMethod:@"GET"];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 保护方法
            if (data == nil) {
                return ;
            }
            NSDictionary *rootDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            NSArray *array = rootDictionary[@"result"];
            self.dataArray = [NSMutableArray array];
            // 遍历数组
            for (NSDictionary *dic in array) {
                ArticleModel *model = [[ArticleModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }];
        [dataTask resume];
    });
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
